let todoList = [];
// 已办理列表
let todoListElement = document.getElementById("todo-list");
let doneListElement = document.getElementById("done-list");
let todoInputElement = document.getElementById("todo-input");
let todoButtonElement = document.getElementById("add-button");

// 生成id
function getId() {
  const str = "1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
  let id = "";
  for (let i = 0; i < 10; i++) {
    const rondIndex = Math.floor(Math.random() * str.length);
    id += str[rondIndex];
  }
  return id;
}
// 添加任务
// 防抖化

todoButtonElement.addEventListener(
  "click",
  throttle(function () {
    const task = todoInputElement.value;
    console.log(task);
    if (task !== "") {
      addTodo(task);
      renderTodoList();
    }
  }, 2000)
);
// 渲染列表
function renderTodoList() {
  todoListElement.innerHTML = "";
  doneListElement.innerHTML = "";
  for (let i = 0; i < todoList.length; i++) {
    const todo = todoList[i];
    const todoElement = document.createElement("li");

    todoElement.setAttribute("data-id", todo.id);
    if (todo.completed) {
      todoElement.classList.add("todo", "done");
      todoElement.innerHTML = `
          <span class="task">${todo.task}</span>
        `;
      doneListElement.appendChild(todoElement);
    } else {
      todoElement.classList.add("todo");
      todoElement.innerHTML = `
    
      <span class="task">${todo.task}</span>
      <button class="done" onclick=computedTodo('${todo.id}')>完成</button>

      <button class="delete" onclick=deleteTodo('${todo.id}') >删除</button>
    `;
      todoListElement.appendChild(todoElement);
    }
  }
}
// 分离已办
// 完成任务

function computedTodo(id) {
  console.log("完成", id);
  todoList.forEach((todo) => {
    if (todo.id === id) {
      todo.completed = true;
    }
  });
  renderTodoList();
}

// 删除任务
function deleteTodo(id) {
  console.log("删除", id);
  todoList = todoList.filter((todo) => todo.id !== id);
  renderTodoList();
}

// 添加任务
function addTodo(task) {
  const todo = {
    id: getId(),
    task: task,
    completed: false,
    checked: false,
  };
  todoList.push(todo);
}

function throttle(func, delay) {
  let lastTime = 0;
  return function () {
    const nowTime = Date.now();
    if (nowTime - lastTime > delay) {
      lastTime = nowTime;
      func.apply(this, arguments);
    }
  };
}
